package cn.tedu.musicsys.service.impl;

import cn.tedu.musicsys.domain.Collection;
import cn.tedu.musicsys.domain.User;
import cn.tedu.musicsys.mapper.CollectionMapper;
import cn.tedu.musicsys.mapper.UserMapper;
import cn.tedu.musicsys.service.CollectionService;
import cn.tedu.musicsys.utils.Request;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.List;


@Service("collectionService")
public class CollectionServiceImpl implements CollectionService {
	@Autowired
	private CollectionMapper collectionMapper;
	@Autowired
	private UserMapper userMapper;

	@Override
	public boolean collectionChange(HttpServletRequest request, int songId) {
		boolean isCurCollected=true;
		User user=userMapper.selectByUser(Request.getUserFromHttpServletRequest(request));
		Collection collection=collectionMapper.selectByCollection(new Collection(user.getUserId(),songId));
		if(collection==null) {
			//该歌曲没有被收藏
			isCurCollected=false;
			//添加收藏
			collectionMapper.insert(new Collection(user.getUserId(),songId));
		}else {
			//已经被收藏，则取消收藏
			collectionMapper.deleteById(collection.getCollectionId());
		}
		//返回改变后的收藏状态
		return !isCurCollected;
	}
	@Override
	public List<Collection> getAllRecords() {
		return collectionMapper.selectAll();
	}

}
